package givenchy

import org.codehaus.groovy.grails.plugins.springsecurity.Secured
@Secured(['ROLE_ADMIN'])
class AdminController {
    def index = { redirect(action: "taskGroupList", params: params) }
    // 管理taskgroup，列表
    def taskGroupList = {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[taskGroupInstanceList: TaskGroup.list(params)]
	}

    // 管理task，从组来的列表
    def taskListByGroup = {
		//println grailsApplication.config.grails.vip.great
        def taskGroup = TaskGroup.get( params.long("id"))
        if(taskGroup){ 
            params.max = Math.min(params.max ? params.int('max') : 10, 100)
            render(view:"taskList",model:[taskInstanceList: Task.findAllByTaskGroup(taskGroup ,params),
                taskInstanceTotal: Task.countByTaskGroup(taskGroup),
                    id:params.id,taskGroupName:taskGroup.name])
            
        }else{
            flash.message = "没找到任务列表"
            redirect(action: "taskGroupList")
        }
	}

    // 管理task，列表
    def taskList = {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[taskInstanceList: Task.list(params),taskInstanceTotal:Task.count()]
	}


    // 根据对task的操作的不同位置，返回不同的列表位置
    def checkReturn(groupid,messages) {
         if(groupid){
                flash.message = messages
                return redirect(action: "taskListByGroup",id:groupid)
         }else{
                flash.message = messages
                return redirect(action: "taskList")
         }
    }
    // 删除任务
    def taskDelete = {
        def taskInstance = Task.get(params.id)
        if (taskInstance) {
            try {
                taskInstance.delete(flush: true)
                checkReturn(params.groupid,"删除成功")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                checkReturn(params.groupid,"删除失败")
            }
        }
        else {
            checkReturn(params.groupid,"没有找到任务")
        }
    }
    // 删除任务组
    def taskGroupDelete = {
        def taskGroupInstance = TaskGroup.get(params.id)
        if (taskGroupInstance) {
            try {
                taskGroupInstance.tasks.each{
                    taskGroupInstance.removeFromTasks(it)
                    it.delete(flush: true)               
                }
                taskGroupInstance.delete(flush: true)
                flash.message = "删除任务组成功！"
                redirect(action: "taskGroupList")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "删除任务组失败！"
                redirect(action: "taskGroupList")
                return 
            }
        }
        else {
            flash.message = "任务组不存在"
            redirect(action: "taskGroupList")
            return
        }
    }

    // 编辑任务组（TaskGroup）
    def taskGroupEdit = {
        def taskGroupInstance = TaskGroup.get(params.id)
        if (!taskGroupInstance) {
            flash.message = "不存在此任务组"
            redirect(action: "taskGroupList")
        }
        else {
            return [taskGroupInstance: taskGroupInstance]
        }
    }

    def taskGroupUpdate = {
        def taskGroupInstance = TaskGroup.get(params.id)
        if (taskGroupInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (taskGroupInstance.version > version) {
                    
                    taskGroupInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'taskGroup.label', default: 'TaskGroup')] as Object[], "Another user has updated this TaskGroup while you were editing")
                    render(view: "taskGroupEdit", model: [taskGroupInstance: taskGroupInstance])
                    return
                }
            }
            taskGroupInstance.properties = params
            taskGroupInstance.buildHourRate(params.rate)
            if (!taskGroupInstance.hasErrors() && taskGroupInstance.save(flush: true)) {
                flash.message = "更新成功"
                redirect(action: "taskGroupList")
            }
            else {
                render(view: "taskGroupEdit", model: [taskGroupInstance: taskGroupInstance])
            }
        }
        else {
            flash.message = "不存在此任务组"
            redirect(action: "taskGroupList")
        }
    }

    // 任务编辑（task）
    def taskEdit = {
        def taskInstance = Task.get(params.id)
        if (!taskInstance) {
            checkReturn(params.groupid,"没有找到此任务")
        }
        else {
            return [taskInstance: taskInstance,groupid:params.groupid]
        }
    }
    

    def taskUpdate = {
        def taskInstance = Task.get(params.id)
        if (taskInstance) {
            taskInstance.properties = params
      
            if (!taskInstance.hasErrors() && taskInstance.save(flush: true)) {
                checkReturn(params.groupid,"任务【${taskInstance.name}】修改成功")
            }
            else {
                render(view: "taskEdit", model: [taskInstance: taskInstance,groupid:params.groupid])
            }
        }
        else {
            checkReturn(params.groupid,"没有找到任务")
        }
    }


    // 关闭任务
   def close = {
        Task task = Task.get(params.id)
        if (task) {
            task.available = false
            task.save();
        }
        checkReturn(params.groupid,"")
    }

    // 开启任务
    def open = {
        Task task = Task.get(params.id)
        if (task) {
            task.available = true
            task.save();
        }
        checkReturn(params.groupid,"")
    }

    // 查找任务组

    def search = {
        def ipFirst = params.ipfirst?params.ipfirst.toInteger():0
        def ipAfter = params.ipafter?params.ipafter.toInteger():0
        def taskGroupList = TaskGroup.withCriteria {
            if(params.isAd){
                eq('isAd',true)
            }
            if(ipAfter > 0){
                between("requireOfIP", ipFirst, ipAfter)
            }
            firstResult(params.offset?params.int('offset'):0)
            maxResults(10)
        }

        def taskGroupCount = TaskGroup.withCriteria {
            if(params.isAd){
                eq('isAd',true)
            }
            if(ipAfter > 0){
                between("requireOfIP", ipFirst, ipAfter)
            }
        }
        render(view:"taskGroupList",model:[taskGroupInstanceList: taskGroupList,
                taskInstanceTotal: taskGroupCount])
    }
}
